package com.yxsk.relay.job.admin.web.controller;

import com.yxsk.relay.job.admin.data.entity.*;
import com.yxsk.relay.job.admin.data.service.JobAppsService;
import com.yxsk.relay.job.admin.data.service.JobDetailService;
import com.yxsk.relay.job.admin.data.service.JobExecuteLogService;
import com.yxsk.relay.job.admin.data.service.JobTriggerLogService;
import com.yxsk.relay.job.admin.web.common.context.HttpContextUtils;
import com.yxsk.relay.job.admin.web.common.enums.MenuTypeEnum;
import com.yxsk.relay.job.admin.web.common.enums.ResultEnum;
import com.yxsk.relay.job.admin.web.common.exception.RelayAdminWebRuntimeException;
import com.yxsk.relay.job.admin.web.common.utils.EncryptUtil;
import com.yxsk.relay.job.admin.web.entity.Menu;
import com.yxsk.relay.job.admin.web.entity.User;
import com.yxsk.relay.job.admin.web.service.MenuService;
import com.yxsk.relay.job.admin.web.service.UserService;
import com.yxsk.relay.job.component.common.protocol.message.base.ResultResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Author 11376
 * @CreaTime 2019/6/26 17:56
 * @Description
 */
@Controller
public class MainController {

    @Autowired
    private MenuService menuService;
    @Autowired
    private UserService userService;

    @Autowired
    private JobAppsService appsService;

    @Autowired
    private JobDetailService jobDetailService;

    @Autowired
    private JobTriggerLogService triggerLogService;

    @Autowired
    private JobExecuteLogService executeLogService;

    @GetMapping("/")
    public String idnex(Model model) {
        Map<String, Menu> keyMenu = new HashMap<>();
        List<Menu> menus = menuService.getListBySortOk();
        menus.forEach(menu -> keyMenu.put(menu.getId(), menu));
        // 封装菜单树形数据
        Map<Long, Menu> treeMenu = new HashMap<>();
        keyMenu.forEach((id, menu) -> {
            if (!menu.getType().equals(MenuTypeEnum.NOT_MENU.getCode())) {
                if (keyMenu.get(menu.getPid()) != null) {
                    keyMenu.get(menu.getPid()).getChildren().put(String.valueOf(menu.getSort()), menu);
                } else {
                    if (menu.getType().equals(MenuTypeEnum.TOP_LEVEL.getCode())) {
                        treeMenu.put(Long.valueOf(menu.getSort()), menu);
                    }
                }
            }
        });

        model.addAttribute("user", HttpContextUtils.getRequestUser());
        model.addAttribute("treeMenu", treeMenu);
        return "/main";
    }

    @GetMapping("/userInfo")
    public String toUserInfo(Model model) {
        model.addAttribute("user", HttpContextUtils.getRequestUser());
        return "/system/main/userInfo";
    }

    /**
     * 保存修改个人信息
     */
    @PostMapping("/userInfo")
    @ResponseBody
    public ResultResponse userInfo(User user) {
        User original = HttpContextUtils.getRequestUser();
        original.setPhone(user.getPhone());
        original.setEmail(user.getEmail());
        original.setRemark(user.getRemark());
        this.userService.updateById(original);

        Map<String, Object> responseMap = new HashMap<>();
        responseMap.put("url", "/userInfo");
        return ResultResponse.ok("保存成功", responseMap);
    }

    @GetMapping("/editPwd")
    public String toEditPwd() {
        return "/system/main/editPwd";
    }

    /**
     * 保存修改密码
     */
    @PostMapping("/editPwd")
    @ResponseBody
    public ResultResponse editPwd(String original, String password, String confirm) {
        // 判断原来密码是否有误
        User user = HttpContextUtils.getRequestUser();
        if (StringUtils.isEmpty(original) || !user.getPassword().equals(EncryptUtil.encrypt(original, user.getSalt()))) {
            throw new RelayAdminWebRuntimeException(ResultEnum.USER_OLD_PWD_ERROR);
        }

        // 判断密码是否为空
        if (password.isEmpty() || "".equals(password.trim())) {
            throw new RelayAdminWebRuntimeException(ResultEnum.USER_PWD_NULL);
        }

        // 判断两次密码是否一致
        if (!password.equals(confirm)) {
            throw new RelayAdminWebRuntimeException(ResultEnum.USER_INEQUALITY);
        }

        // 修改密码，对密码进行加密
        String salt = UUID.randomUUID().toString().replace("-", "").substring(0, 15);
        String encrypt = EncryptUtil.encrypt(user.getPassword(), salt);
        user.setPassword(encrypt);
        user.setSalt(salt);

        // 保存数据
        userService.updateById(user);
        return ResultResponse.ok("修改成功");
    }

    @GetMapping("/index")
    public String toIndex(Model model) {
        model.addAttribute("apps", this.appsService.findAllNormalEntities());
        model.addAttribute("jobs", this.jobDetailService.findAllNormalEntities());

        // 查询应用总数
        JobApps apps = new JobApps();
        apps.setDelFlag(BaseEntity.DelFlagEnum.NORMAL.getFlag());
        model.addAttribute("appCount", this.appsService.count(apps));
        // 查询任务总数
        JobDetails details = new JobDetails();
        details.setDelFlag(BaseEntity.DelFlagEnum.NORMAL.getFlag());
        model.addAttribute("jobCount", this.jobDetailService.count(details));
        // 查询触发任务次数
        JobTriggerLog log = new JobTriggerLog();
        log.setDelFlag(BaseEntity.DelFlagEnum.NORMAL.getFlag());
        model.addAttribute("triggerCount", this.triggerLogService.count(log));
        // 查询执行任务次数
        JobExecuteLog executeLog = new JobExecuteLog();
        executeLog.setDelFlag(BaseEntity.DelFlagEnum.NORMAL.getFlag());
        model.addAttribute("executeCount", this.executeLogService.count(executeLog));
        return "/system/main/index";
    }
}